#include <stdio.h>
#include <getopt.h>
#include <unistd.h>
#include <stdlib.h>

option longOpt[] = {
    {"time", required_argument, NULL, 't'},
    {"cpu",  required_argument, NULL, 'c'},
    {"help", no_argument,       NULL, 'h'},
    {NULL,   no_argument,       NULL, 0}
};
static const char *optString = "t:c:h";
void usage(char* procName) {
    printf("usage: %s option argument\n", procName);
    printf("       -c --cpu [cpu id] select the cpu id. default cpu 0\n");
    printf("       -t --time [ms] set the inteval time. default 1000ms\n");
    printf("       -h --help get this help information.\n");
    exit(0);
}
char msr_path[32];
int main(int argc, char** argv) {
    int opt, longIndex;
    int cpu = 0, intevalTime = 1000;
    opt = getopt_long(argc, argv, optString, longOpt, &longIndex);
    if (opt == -1) {
        usage(argv[0]);
    }
    while (opt != -1) {
        switch(opt) {
            case 'c':
                cpu = atoi(optarg);
                break;
            case 't':
                intevalTime = atoi(optarg);
                break;
            case 'h':
            case 0:
            default:
                usage(argv[0]);
                break;
        }
        opt = getopt_long(argc, argv, optString, longOpt, &longIndex);
    }
    sprintf(msr_path, "/dev/cpu/%d/msr", cpu);
    long val;
    while (1) {
        FILE* f = fopen(msr_path, "r");
        fseek(f, 0x639, SEEK_CUR);
        fread(&val, sizeof(val), 1, f);
        printf("%x\n", val);
        double power = (double) val / 65536; //16384 ;
        printf("the power of cpu %d is %f watts.\n", cpu, power);
        usleep(1000*intevalTime);
        fclose(f);
    }
    return 0;
}
